package com.spi.controller;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.stream.Collectors;

@RequestMapping("/pdf")
@RestController
public class PdfController02 {

    @RequestMapping("/test02")
    public void test02() {
        // 从配置文件中读取文件路径
        String inputPath = "D:\\555\\pdftest\\文档1.pdf";
        String outputPath = "D:\\555\\pdftest\\1.pdf";

        try (PDDocument document = PDDocument.load(new File(inputPath))) {
            // 压缩图像
            compressImages(document, 0.2f, 150); // 设置图像质量为 20%，分辨率降为 150 DPI

            // 删除不必要的元数据
            removeMetadata(document);

            // 优化 PDF 文件
            optimizePdf(document,outputPath);

            // 保存压缩后的PDF文档
            document.save(outputPath);
        } catch (IOException e) {
            // 记录日志或提供用户友好的错误信息
            System.err.println("处理PDF文档时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void removeMetadata(PDDocument document) {
        PDMetadata metadata = document.getDocumentCatalog().getMetadata();
        if (metadata != null) {
            System.out.println("Removing metadata");
            document.getDocumentCatalog().setMetadata(null);
        }
    }
    private static void compressImages(PDDocument document, float quality, int dpi) throws IOException {
        PDPageTree pages = document.getDocumentCatalog().getPages();
        for (PDPage page : pages) {
            for (COSName name : page.getResources().getXObjectNames()) {
                if (name != null) {
                    Object xObject = page.getResources().getXObject(name);
                    if (xObject instanceof PDImageXObject) {
                        PDImageXObject image = (PDImageXObject) xObject;
                        System.out.println("Processing image: " + name);

                        BufferedImage bufferedImage = image.getImage();
                        if (bufferedImage == null) {
                            System.err.println("Failed to get image for: " + name);
                            continue;
                        }

                        // 降低图像分辨率
                        double scale = (double) dpi / 300; // 300 DPI 是常见的高分辨率
                        int newWidth = (int) (bufferedImage.getWidth() * scale);
                        int newHeight = (int) (bufferedImage.getHeight() * scale);
                        BufferedImage resizedImage = resizeImage(bufferedImage, newWidth, newHeight);

                        File tempFile = File.createTempFile("temp", ".jpg");
                        if (!ImageIO.write(resizedImage, "JPEG", tempFile)) {
                            System.err.println("Failed to write image to temporary file: " + tempFile.getAbsolutePath());
                            continue;
                        }

                        // 读取压缩后的图像并创建 PDImageXObject
                        try (FileInputStream fis = new FileInputStream(tempFile)) {
                            BufferedImage readImage = ImageIO.read(fis);
                            if (readImage == null) {
                                System.err.println("Failed to read image from temporary file: " + tempFile.getAbsolutePath());
                                continue;
                            }

                            PDImageXObject compressedImage = JPEGFactory.createFromImage(document, readImage, quality);
                            if (compressedImage == null) {
                                System.err.println("Failed to create compressed image for: " + name);
                                continue;
                            }

                            page.getResources().put(name, compressedImage);
                            System.out.println("Replaced image: " + name);
                        } finally {
                            tempFile.delete();
                        }
                    }
                }
            }
        }
    }

    private static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, originalImage.getType());
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
        g2d.dispose();
        return resizedImage;
    }
    private static void optimizePdf(PDDocument document, String outputPath) throws IOException {
        // 使用 PDFMergerUtility 进行优化
        PDFMergerUtility merger = new PDFMergerUtility();
        File tempFile = File.createTempFile("temp", ".pdf");
        document.save(tempFile);

        // 添加临时文件作为源
        merger.addSource(tempFile);
        merger.setDestinationFileName(outputPath);

        // 合并并优化文档
        merger.mergeDocuments(null);

        // 删除临时文件
        tempFile.delete();

        System.out.println("Optimizing PDF document");

        System.out.println("Optimizing PDF document");
    }
}
